<?php
namespace app\admin\controller;

use think\Db;

class Goods extends Base{

	/**
	 * [站点代买/销售商品类别列表]
	 */
	public function cate() {
		if($this->request->isPost()){
			$data = DB::name('goods_cate')->where('pid','<>',0)->order('pid asc')->order('id asc')->select();
			foreach($data as $k => $v){
				$data[$k]['row_num'] = DB::name('goods_cate')->where('pid',$v['pid'])->count();
			}
			return ['code'=>1,'msg'=>'表格加载成功','data'=>$data];
		}
		return $this->fetch();
	}
	/**
	 * [添加商品分类]
	 */
	public function addcate() {
		$param = input('post.');
		if($param['is_top'] == 1){
			DB::startTrans();
			try{
				$insID = DB::name('goods_cate')->insertGetId([
					'name' => $param['name']
				]);
				// 插入一条默认子级
				DB::name('goods_cate')->insert([
					'pid' => $insID,
					'name' => '请修改',
					'belonged_name' => $param['name'],
					'rowspan' => 'false'
				]);
				DB::commit();
				return ['code'=>1,'msg'=>'添加成功'];
			}catch(\Exception $e){
				DB::rollback();
				return ['code'=>0,'msg'=>'添加失败：'.$e->getMessage()];
			}
		}else{
			unset($param['is_top']);
			unset($param['id']);
			$res = DB::name('goods_cate')->insert($param);
			if($res !== false){
				return ['code'=>1,'msg'=>'添加成功'];
			}else{
				return ['code'=>0,'msg'=>'添加失败'];
			}
		}
	}
	/**
	 * [编辑商品分类]
	 */
	public function editcate() {
		$param = input('post.');
		if($param['is_top'] == 1){
			DB::startTrans();
			try{
				DB::name('goods_cate')->where('id',$param['pid'])->update([
					'name' => $param['name']
				]);
				DB::name('goods_cate')->where('pid',$param['pid'])->update([
					'belonged_name' => $param['name']
				]);
				DB::commit();
				return ['code'=>1,'msg'=>'编辑成功'];
			}catch(\Exception $e){
				DB::rollback();
				return ['code'=>0,'msg'=>'编辑失败：'.$e->getMessage()];
			}
		}else{
			$res = DB::name('goods_cate')->where('id',$param['id'])->update($param);
			if($res !== false){
				return ['code'=>1,'msg'=>'更新成功'];
			}else{
				return ['code'=>0,'msg'=>'更新失败'];
			}
		}
	}
	/**
	 * [删除商品分类]
	 */
	public function delcate() {
		$param = input('post.');
		DB::startTrans();
		try{
			if($param['is_top'] == 1){
				DB::name('goods_cate')->where('id',$param['id'])->delete();
				DB::name('goods_cate')->where('pid',$param['id'])->delete();
			}else{
				$count = DB::name('goods_cate')->where('pid',$param['pid'])->count();
				// 如果只剩一条重置 否则 删除
				if($count == 1){
					DB::name('goods_cate')->where('id',$param['id'])->update([
						'name'=>'请修改','commid'=>'','commid_2'=>''
					]);
				}else{
					DB::name('goods_cate')->where('id',$param['id'])->delete();
				}
				//设置rowspan
				$id = DB::name('goods_cate')->where('pid',$param['pid'])->order('id asc')->value('id');
				DB::name('goods_cate')->where('id',$id)->update(['rowspan'=>'false']);
			}
			DB::commit();
			return ['code'=>1,'msg'=>'删除成功'];
		}catch(\Exception $e){
			DB::rollback();
			return ['code'=>0,'msg'=>'删除失败:'.$e->getMessage()];
		}
	}
}
